#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main()
{
    pid_t pid = fork();
    
    if(pid < 0)
    {
        perror("fork");
        exit(-1);
    }
    else if(pid == 0)
    {
        //子进程
        int count = 5;
        while(count)
        {
            printf("cnt:%d我是子进程，pid = %d, ppid = %d\n", count, getpid(), getppid());
            sleep(1);
            count--;
        }
        exit(12); 
    } 
    else 
    { 
        printf("我是父进程，pid = %d, ppid = %d\n", getpid(), getppid()); 
        
        //非阻塞式等待
        int quit = 0;
        while(!quit)
        {
            int status = 0;
            pid_t ret = waitpid(-1, &status, WNOHANG);

            if(ret > 0)
            {
                //等待成功 && 子进程退出
                printf("等待子进程退出成功, 退出码：%d\n", WEXITSTATUS(status));
                sleep(1);
                quit = 1;
            }
            else if(ret == 0)
            {
                //等待成功 && 子进程还没有退出
                printf("子进程还在运行中，暂时还没有退出，父进程可以再等一等，处理一下其他事情？？？\n");
                sleep(1);
            }
            else 
            {
                //等待失败
                printf("wait失败!!!\n");
                quit = -1;
            }
        }

        //阻塞式等待
        //pid_t ret = wait(NULL); 
        //pid > 0 -> 等待指定子进程退出 
        //pid = -1 -> 等待任意子进程退出 
         
        //int status = 0; 
        //pid_t ret = waitpid(pid, &status, option); 
        //pid_t ret = waitpid(-1, &status, 0);//阻塞式的等待
        //if(ret > 0)
        //{
        //    if(WIFEXITED(status))
        //    {
        //        printf("等待子进程成功退出，退出码：%d\n", WEXITSTATUS(status));
        //    }
        //    else 
        //    {
        //        printf("子进程异常退出，%d\n", WIFEXITED(status));
        //    }
        //}
    }

    return 0;
}
